<?php

namespace app\common\controller;

use app\common\exception\BaseException;
use think\facade\Cache;

class ApiController extends CommonController
{
    protected mixed $companyId;

    protected string $appName = 'mini';
    /**
     * @var int|mixed
     */
    protected mixed $scene_id;

    /**
     * @throws BaseException
     */
    protected function initialize(): void
    {
        parent::initialize();
        $this->needLogin = $this->checkLogin();
        $this->userInfo  = $this->getUser();
        $this->uid       = $this->userInfo['id'] ?? 0;
        $this->companyId = $this->userInfo['company_id'] ?? 0;
        $this->scene_id  = $this->userInfo['scene_id'] ?? 0;
    }

    /**
     * @throws BaseException
     */
    protected function getUser(): mixed
    {
        if(!$this->needLogin) return [];

        if (!$token = $this->request->header('token')) {
            throw new BaseException(['message' => '缺少必要参数：token']);
        }

        if (!$user = Cache::get($token)) {
            throw new BaseException(['message' => '登录已过期，请重新登录','status'=>401]);
        }

        if(isset($user['delete_time']) && $user['delete_time']){
            Cache::delete($token);
            throw new BaseException(['message' => '账号已被删除']);
        }
        return $user;
    }

    protected function checkLogin():bool
    {
        $commonConfig = config('common');
        $noAuthCon    = $commonConfig['no_auth_mini_controller'];
        $thatCon      = strtolower($this->request->controller());
        if(in_array($thatCon, $noAuthCon, true)) return false;
        return true;
    }
}